#include <iostream>
#include <string.h>     //memset()
#include <unistd.h>	//fork()
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>	//exit()
#include <netinet/in.h>
#include <arpa/inet.h>
#include <wait.h>

using namespace std;


int main (void)
{
	int socketfd, sin_size, client_fd, clild_pid, status;
	struct sockaddr_in addr, remote_addr;

	if ( (socketfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
	{
		perror("socket");
		cout << socketfd << endl;
		exit(1);
	}

	memset(&addr, 0, sizeof(addr));
	addr.sin_port = 1024;
	addr.sin_addr.s_addr = INADDR_ANY;
	
	if (bind(socketfd, (struct sockaddr *)&addr, sizeof(addr)))
	{
		perror("bind");
		exit(1);
	}
	if (listen(socketfd, 10) < 0)
	{
		perror("listen");
		exit(1);
	}
	
	while (1)
	{
		sin_size = sizeof(struct sockaddr_in);
		cout << __LINE__ << endl;
		if ((client_fd = accept(socketfd, (struct sockaddr *)&remote_addr, (socklen_t *)&sin_size)) == -1)
		{
			perror("accept出错");
			continue;
		}
		printf("received a connection from %s\n", inet_ntoa(remote_addr.sin_addr));
		if ( 0 == (clild_pid = fork()))
		{ /* 子进程代码段 */
			if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)
			{
				perror("send出错！");
			}
			close(client_fd);
			exit(0);
		}
		wait(&status);
		close(client_fd);
	}
	close(socketfd);
	return 0;
}

